import waves from "@/directive/waves"; // Waves directive
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
import { alertMessage, alertWithCallback, isValidateNull } from "@/utils/utils";
import { mapGetters } from 'vuex';
import selectDevice from "@/business-components/select-device/select-device";
import carDetail from "@/business-components/car-detail/car-detail"
import {
  getCarJZ,
  getCompanyItems,
  getCategoryAndTypes,
  getCarStatus,
  getCars,
  saveCar,
  toggleCarStatus, setDevices
} from "@/views/car-manage/car.service";

export default {
  components: { Pagination, selectDevice, carDetail },
  directives: { waves },
  data() {
    return {
      file_url: process.env.VUE_APP_FILE_URL, // 头像url
      recordNum: 20, // 分页组件默认的页数, 分页里的select默认10, 20, 50
      totalNum: 0, // 数据总数
      pageNum: 1, // 页数
      data: [], // 用户列表
      dialogTitle: '', // 表单标题
      searchCriteria: {}, // 搜索条件
      editDialogVisible: false, // 编辑详情模态窗
      editForm: {
        brandInfo: {}
      }, // 表单
      editRules: {
        vehicleName: [{ required: true, trigger: "change", validator: isValidateNull }],
        enumMedium: [{ required: true, trigger: "change", validator: isValidateNull }],
        transportId: [{ required: true, trigger: "change", validator: isValidateNull }],
        licensePlate: [{ required: true, trigger: "change", validator: isValidateNull }]
      }, // 表单效验规则
      showSelectCarDialog: false, // 选择车辆
      selectedData: {}, // 选中数据
      showSelectCarDetailDialog: false, // 车辆详情
      categories: [], // 车辆品类
      categoryItems: [], // 品牌型号
      companies: [], // 运输单位
      carStatus: [], // 运输状态
      jzItems: [], // 介质列表
      checkedRows: [], // table checkbox选中数据
      vehicleId: 0,
      equipId: 0
    }
  },
  computed: {
    ...mapGetters([
      'codesCheck'
    ])
  },
  created() {
    this.getCompanyList();
    this.getCarStatus();
    this.getDataList();
  },
  methods: {
    // 获取列表
    getDataList() {
      this.searchCriteria.pageNum = this.pageNum;
      this.searchCriteria.recordNum = this.recordNum;
      getCars(this.searchCriteria).then(res => {
        this.totalNum = res.dataCount;
        this.data = res.data;
      });
    },

    // 根据关键字进行搜索
    search() {
      this.pageNum = 1;
      this.getDataList();
    },

    // 重置搜索
    reset() {
      this.pageNum = 1;
      this.searchCriteria = {};
      this.getDataList();
    },

    // 运输单位列表
    getCompanyList() {
      getCompanyItems().then(res => {
        this.companies = res.data;
      });
    },

    // 获取车辆品牌和型号
    getCarItems() {
      getCategoryAndTypes().then(res => {
        this.categories = res.data;
        this.handleCategoryChange(false);
      });
    },

    // 获取车辆品牌和型号
    getJZItems() {
      getCarJZ().then(res => {
        this.jzItems = res.data;
      });
    },

    // 获取车辆品牌和型号
    getCarStatus() {
      getCarStatus().then(res => {
        this.carStatus = res.data;
      });
    },

    // 处理checkbox选中行数据
    handleSelectionChange(val) {
      this.checkedRows = val;
    },

    // 打开新建、编辑窗体
    openEditDialog(type, selectedData) {
      this.getCarItems();
      this.getJZItems();
      if (type === 'create') {
        this.dialogTitle = '新增车辆';
        this.$nextTick(() => {
          // 重置必填项
          this.editForm = {
            brandInfo: {
              brandId: '',
              modelId: ''
            },
            vehiclePhoto: ''
          };
          this.$refs.dataForm.resetFields();
        });
      } else {
        this.dialogTitle = '编辑车辆';
        this.$nextTick(() => {
          this.editForm = Object.assign({}, selectedData);
          this.$refs.dataForm.resetFields();
        });
      }
      this.editDialogVisible = true;
    },

    // 创建或者编辑信息
    save() {
      // 表单验证
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          saveCar(this.editForm).then((res) => {
            this.editDialogVisible = false;
            alertMessage(res.message);
            this.reset();
          }).catch(() => {}); // 关闭confirm框的回调，不处理的话会报一个js error
        }
      });
    },

    // 显示关联车辆
    showCarDialog(rowData) {
      this.selectedData = rowData;
      this.showSelectCarDialog = true;
    },

    // 显示车辆详情
    showCarDetailDialog(rowData) {
      this.showSelectCarDetailDialog = true;
      // this.equipId = rowData.objectId;
      this.vehicleId = rowData.objectId;
    },

    // 上传头像
    handleAvatarSuccess(res, file) {
      this.editForm.vehiclePhoto = res.data;
    },

    // 删除头像
    handleAvatarRemove() {
      this.editForm.vehiclePhoto = '';
    },

    // 切换品牌
    handleCategoryChange(clearModel = true) {
      if (clearModel) {
        this.editForm.brandInfo.modelId = '';
      }
      if (this.editForm.brandInfo.brandId == '') {
        this.categoryItems = [];
      } else {
        const selectedCategory = this.categories.filter(item => {
          return item.objectId == this.editForm.brandInfo.brandId;
        });
        this.categoryItems = selectedCategory[0].modelList;
      }
    },

    // 切换车辆状态
    toggleCarStatus(id, status) {
      alertWithCallback('此操作将更新车辆状态, 是否继续?', '提示').then(() => {
        toggleCarStatus(id, status).then(res => {
          alertMessage(res.message);
          this.reset();
        });
      }).catch(() => {}); // 关闭confirm框的回调，不处理的话会报一个js error
    },

    // 关联设备
    setDevices(e) {
      const params = {
        equipmentIds: [],
        vehicleId: this.selectedData.objectId
      };
      e.forEach(item => {
        params.equipmentIds.push(item.objectId);
      });
      setDevices(params).then(res => {
        alertMessage(res.message);
        this.reset();
      });
    }
  }
}
